import SparkMD5 from 'spark-md5'

export default function(file, callback) {
  const blobSlice =
    File.prototype.slice ||
    File.prototype.mozSlice ||
    File.prototype.webkitSlice
  const chunkSize = 2097152 // Read in chunks of 2MB
  const chunks = Math.ceil(file.size / chunkSize)
  let currentChunk = 0
  const spark = new SparkMD5.ArrayBuffer()
  const fileReader = new FileReader()

  function loadNext() {
    const start = currentChunk * chunkSize
    const end = start + chunkSize >= file.size ? file.size : start + chunkSize
    fileReader.readAsArrayBuffer(blobSlice.call(file, start, end))
  }

  fileReader.onload = e => {
    spark.append(e.target.result) // Append array buffer
    currentChunk += 1

    if (currentChunk < chunks) {
      loadNext()
    } else {
      callback(true, spark.end())
      console.log('finished loading')
    }
  }

  fileReader.onerror = () => {
    callback(false, 'oops, something went wrong.')
  }

  loadNext()
}
